package std

import (
	"fmt"
	"strconv"
	"strings"
)

// PhoneKeepNumbersOnly 只保留下数字
func PhoneKeepNumbersOnly(phone string) string {
	var rt []byte
	for i := 0; i < len(phone); i++ {
		if phone[i] >= '0' && phone[i] <= '9' {
			rt = append(rt, phone[i])
		}
	}
	return string(rt)
}

// IsPhone 判断是否是手机号码的组成
func IsPhone(s string) bool {
	if len(s) <= 2 {
		return false
	}
	if s[0] == '+' {
		s = s[1:]
	}
	for _, d := range s {
		if d < '0' || d > '9' {
			return false
		}
	}
	return true
}

// AutoAddAreaCode 自动增加区号
// 如果返回空字符串，则表示不是合格的手机号
func AutoAddAreaCode(areaCode string, phone string) string {
	phone = deleteAllSpace(phone)
	if len(phone) <= 1 || false == IsPhone(phone) {
		return ""
	}
	if areaCode[0] == '+' {
		areaCode = areaCode[1:]
	}
	if phone[0] == '+' {
		phone = phone[1:]
	}
	if len(areaCode) >= len(phone) {
		return ""
	}
	if strings.HasPrefix(phone, areaCode) { //先去除掉前面的区号
		phone = phone[len(areaCode):]
	}
	phoneNumber, err := strconv.ParseInt(phone, 10, 64)
	if err != nil {
		return ""
	}
	return fmt.Sprint("+", areaCode, phoneNumber)
}

// AutoDelAreaCode 自动移除区号
func AutoDelAreaCode(areaCode string, phone string) string {
	phone = deleteAllSpace(phone)
	if len(phone) <= 1 || false == IsPhone(phone) {
		return ""
	}
	if phone[0] == '+' {
		phone = phone[1:]
	}
	if areaCode[0] == '+' {
		areaCode = areaCode[1:]
	}
	if len(areaCode) >= len(phone) {
		return ""
	}
	if strings.HasPrefix(phone, areaCode) { //去除掉前面的区号
		phone = phone[len(areaCode):]
	}
	phoneNumber, err := strconv.ParseInt(phone, 10, 64)
	if err != nil {
		return ""
	}
	return fmt.Sprint(phoneNumber)
}

// deleteAllSpace 删除掉空格，tab，回车，换行
func deleteAllSpace(s string) string {
	var temp = make([]byte, len(s))
	var index = 0
	for i := 0; i < len(s); i++ {
		if s[i] < 0x80 {
			switch s[i] {
			case ' ', '\t', '\n', '\v', '\f', '\r':
				continue
			}
		}
		temp[index] = s[i]
		index++
	}
	s = strings.ReplaceAll(string(temp[:index]), string(0x85), "")
	s = strings.ReplaceAll(s, string(0xA0), "")
	return s
}
